<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            body {
                display: flex;
                flex-wrap: wrap;
            }
            #box {
                margin: auto;
            }
            table {
                width: 800px;
            }
            td {
                text-align: center;
            }
            #box2 {
                margin: auto;
            }
        </style>
    </head>
    <body>
        <div id="box">
            <h1>真划算</h1>
            <table border="1">
                <thead>
                    <tr>
                        <th>商品</th>
                        <th>单价（元）</th>
                        <th>颜色</th>
                        <th>库存</th>
                        <th>好评率</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <br />
        <div id="box2">
            <h1>购物车</h1>
            <table border="1">
                <thead>
                    <tr>
                        <th>商品</th>
                        <th>单价（元）</th>
                        <th>数量</th>
                        <th>金额</th>
                        <th>删除</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <h3>总计：<span>0</span>￥</h3>
        </div>
    </body>
    <script>
        //页面加载完毕之后
        window.onload = function () {
            //获取商品列表数据
            let goodsList = getGoodsList()
            //渲染商品列表
            renderGoodsList(goodsList)
            //获取购物车数据
            let shopCarList = getShopCarList()
            //渲染购物车
            renderShopCar(shopCarList)

            document
                .querySelector('#box tbody')
                .addEventListener('click', addShopCarFun)
            document
                .querySelector('#box2 tbody')
                .addEventListener('click', downShopCarFun)
            document
                .querySelector('#box2 tbody')
                .addEventListener('change', downShopCarFun)
        }
        function downShopCarFun() {
            if (event.target.nodeName == 'BUTTON') {
                let index = event.target.getAttribute('index')
                let shopCarList = getShopCarList()
                let goodsList = getGoodsList()
                if (event.target.innerHTML == '-') {
                    if (shopCarList[index].num < 2) {
                        alert('不能再减了最少买一件')
                        return
                    }
                    shopCarList[index].num--
                    let gIndex = goodsList.findIndex((item) => {
                        return item.id == shopCarList[index].id
                    })
                    goodsList[gIndex].stock++
                }
                if (event.target.innerHTML == '+') {
                    let gIndex = goodsList.findIndex((item) => {
                        return item.id == shopCarList[index].id
                    })
                    if (goodsList[gIndex].stock == 0) {
                        alert('库存不足')
                        return
                    }
                    shopCarList[index].num++
                    goodsList[gIndex].stock--
                }
                if (event.target.innerHTML == '删除') {
                    let gIndex = goodsList.findIndex((item) => {
                        return item.id == shopCarList[index].id
                    })
                    goodsList[gIndex].stock += shopCarList[index].num
                    shopCarList.splice(index, 1)
                }
                localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
                localStorage.setItem('goodsList', JSON.stringify(goodsList))
                renderShopCar(shopCarList)
                renderGoodsList(goodsList)
            }
            if (event.target.nodeName == 'INPUT' && event.type != 'click') {
                let n = event.target.value
                let reg = /^\d+$/
                let shopCarList = getShopCarList()
                let index = event.target.getAttribute('index')
                let goodsList = getGoodsList()
                let gIndex = goodsList.findIndex((item) => {
                    return item.id == shopCarList[index].id
                })
                if (!reg.test(n)) {
                    alert('请输入数字')
                    event.target.value = shopCarList[index].num
                    return
                }
                if (+event.target.value < shopCarList[index].num) {
                    let cha = shopCarList[index].num - event.target.value
                    goodsList[gIndex].stock += cha
                    shopCarList[index].num = event.target.value
                } else if (goodsList[gIndex].stock < event.target.value) {
                    alert('库存只剩' + goodsList[gIndex].stock + '件')
                    event.target.value =
                        +shopCarList[index].num + +goodsList[gIndex].stock
                    goodsList[gIndex].stock = 0
                    shopCarList[index].num = event.target.value
                }

                localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
                localStorage.setItem('goodsList', JSON.stringify(goodsList))
                renderShopCar(shopCarList)
                renderGoodsList(goodsList)
            }
        }
        //加入购物车函数
        function addShopCarFun() {
            if (event.target.nodeName == 'BUTTON') {
                let index = event.target.getAttribute('index')
                let goodsList = getGoodsList()
                let shopCarList = getShopCarList()
                //判断购物车中是否有该商品
                let sIndex = shopCarList.findIndex((item) => {
                    return item.id == goodsList[index].id
                })
                if (sIndex == -1) {
                    shopCarList.push({
                        id: goodsList[index].id,
                        goodsName: goodsList[index].goodsName,
                        price: goodsList[index].price,
                        num: 1,
                    })
                    goodsList[index].stock--
                } else {
                    if (goodsList[index].stock == 0) {
                        alert('库存不足')
                        return
                    }
                    shopCarList[sIndex].num++
                    goodsList[index].stock--
                }
                //保存购物车数据
                localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
                localStorage.setItem('goodsList', JSON.stringify(goodsList))
                renderShopCar(shopCarList)
                renderGoodsList(goodsList)
            }
        }
        //获取购物车列表
        function getShopCarList() {
            let data = localStorage.getItem('shopCarList')
            if (data) {
                return JSON.parse(data)
            } else {
                return []
            }
        }
        //获取商品列表数据
        function getGoodsList() {
            let data = localStorage.getItem('goodsList')
            if (data) {
                return JSON.parse(data)
            } else {
                return [
                    {
                        id: 1,
                        goodsName: '苹果',
                        price: 10,
                        color: 'red',
                        stock: 100,
                        goodRate: 99,
                    },
                    {
                        id: 2,
                        goodsName: '香蕉',
                        price: 15,
                        color: '黄色',
                        stock: 100,
                        goodRate: 99,
                    },
                    {
                        id: 3,
                        goodsName: '哈密瓜',
                        price: 20,
                        color: '绿色',
                        stock: 100,
                        goodRate: 99,
                    },
                ]
            }
        }
        //渲染商品列表
        function renderGoodsList(data) {
            let html = ''
            data.forEach((item, index) => {
                html += `<tr>
                                    <td>${item.goodsName}</td>
                                    <td>${item.price}</td>
                                    <td>${item.color}</td>
                                    <td>${item.stock}</td>
                                    <td>${item.goodRate}</td>
                                    <td><button index="${index}">加入购物车</button></td>
                                </tr>`
            })
            document.querySelector('#box tbody').innerHTML = html
        }
        //渲染购物车列表
        function renderShopCar(data) {
            let html = ''
            data.forEach((item, index) => {
                html += ` <tr>
                                <td>${item.goodsName}</td>
                                <td>${item.price}</td>
                                <td>
                                    <button class="btn" index="${index}">-</button
                                    ><input index="${index}" type="text" value="${
                    item.num
                }" /><button class="btn" index="${index}">+</button>
                                </td>
                                <td>${item.price * item.num}</td>
                                <td><button index="${index}">删除</button></td>
                            </tr>`
            })
            document.querySelector('#box2 tbody').innerHTML = html
            countPrice()
        }
        function countPrice() {
            let shopCarList = getShopCarList()
            let price = 0
            shopCarList.forEach((item) => {
                price += item.price * item.num
            })
            document.querySelector('#box2 span').innerHTML = price
        }
    </script>
    <style>
        .btn {
            width: 30px;
        }
    </style>
</html>
